var router = require('koa-router')();

router.get('/list', httpResult.resp (async ctx => {
  let admin = ctx.session.admin;
  let query = ctx.query;
  let q = _.assign(query, {customer_chain: new RegExp(`^${admin.customer_chain}`)});
  return await models.media.find(q, {name : 1, file_id : 1, size : 1, create_time : 1, tags : 1, status : 1, type : 1});
}));

router.post('/', httpResult.resp(async ctx => {
  let admin = ctx.session.admin;
  let data = ctx.request.body;
  ctx.assert(data.type, 'missing params: type');
  ctx.assert(data.name, 'missing params: name');

  let info = {
    name : data.name,
    type : data.type,
    customer_name   : admin.customer_name,
    customer_chain  : admin.customer_chain,
    creator         : admin._id,  //对应adminUserModel 的objectId  //除超级管理员外，都有creator
    create_time     : new Date(),//upload time
  };
  if(data.type < 4){
    ctx.assert(data.file_id, 'missing params: file_id');
    let fileMeta = await gfs.files.findOne({_id: gfs.tryParseObjectId(data.file_id)});
    ctx.assert(fileMeta, '文件不存在');

    info.file_id = data.file_id;
    info.filename = fileMeta.filename;
    info.size = fileMeta.size;
  }
  let result;
  if(data.id){
    result = await models.media.findOneAndUpdate({_id : data.id}, {$set : {name: data.name}}, {returnNewDocument : true});
  }else{
    result = await models.media.create(info);
  }
  return result
}));

router.del('/', httpResult.resp(async ctx => {
  let admin = ctx.session.admin;
  let data = ctx.request.body;

  ctx.assert(data.id, 'missing params: id');
  let mediaInfo = await models.media.findOne({
    _id: data.id,
    customer_chain: new RegExp(`^${admin.customer_chain}`)
  });
  ctx.assert(mediaInfo, '文件不存在或权限不足');
  if(mediaInfo.type === 4){
    await models.menu.deleteMany({media_id : mediaInfo._id});
  }else{
    await gfs.files.deleteOne({_id : mediaInfo.file_id});
  }

  return await mediaInfo.deleteOne();
}));

module.exports = router;
